document.addEventListener('DOMContentLoaded', () => {
    // Form elements
    const loginForm = document.getElementById('loginForm');
    const emailInput = document.getElementById('email');
    const passwordInput = document.getElementById('password');
    const rememberMeCheckbox = document.getElementById('rememberMe');

    // Input animation
    const formInputs = document.querySelectorAll('.form-group input');
    formInputs.forEach(input => {
        // Handle initial state if input has value (e.g., from autocomplete)
        if (input.value) {
            input.nextElementSibling.classList.add('active');
        }

        // Handle input focus and blur events
        input.addEventListener('focus', () => {
            input.nextElementSibling.classList.add('active');
        });

        input.addEventListener('blur', () => {
            if (!input.value) {
                input.nextElementSibling.classList.remove('active');
            }
        });
    });

    // Form validation
    const validateEmail = (email) => {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email.toLowerCase());
    };

    const validatePassword = (password) => {
        return password.length >= 6;
    };

    const showError = (element, message) => {
        const formGroup = element.closest('.form-group');
        const errorElement = formGroup.querySelector('.error-message') || 
            (() => {
                const error = document.createElement('div');
                error.className = 'error-message';
                formGroup.appendChild(error);
                return error;
            })();
        
        errorElement.textContent = message;
        errorElement.style.color = '#ff6b6b';
        errorElement.style.fontSize = '0.85em';
        errorElement.style.marginTop = '5px';
        element.classList.add('error');
    };

    const clearError = (element) => {
        const formGroup = element.closest('.form-group');
        const errorElement = formGroup.querySelector('.error-message');
        if (errorElement) {
            errorElement.remove();
        }
        element.classList.remove('error');
    };

    // Handle form submission
    loginForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        let isValid = true;

        // Clear previous errors
        clearError(emailInput);
        clearError(passwordInput);

        // Validate email
        if (!validateEmail(emailInput.value)) {
            showError(emailInput, '请输入有效的邮箱地址');
            isValid = false;
        }

        // Validate password
        if (!validatePassword(passwordInput.value)) {
            showError(passwordInput, '密码至少需要6个字符');
            isValid = false;
        }

        if (isValid) {
            const loginButton = document.querySelector('.login-button');
            loginButton.disabled = true;
            loginButton.style.opacity = '0.7';
            loginButton.textContent = '登录中...';

            try {
                // Simulate API call
                await new Promise(resolve => setTimeout(resolve, 1500));

                // Here you would typically make an actual API call to your backend
                // const response = await fetch('/api/login', {
                //     method: 'POST',
                //     headers: {
                //         'Content-Type': 'application/json',
                //     },
                //     body: JSON.stringify({
                //         email: emailInput.value,
                //         password: passwordInput.value,
                //         rememberMe: rememberMeCheckbox.checked
                //     })
                // });

                // if (response.ok) {
                //     const data = await response.json();
                //     // Handle successful login
                // }

                // For demo purposes, redirect to index page
                window.location.href = 'index.html';
            } catch (error) {
                console.error('Login error:', error);
                // Show error message
                const errorContainer = document.createElement('div');
                errorContainer.className = 'login-error';
                errorContainer.textContent = '登录失败，请稍后重试';
                errorContainer.style.color = '#ff6b6b';
                errorContainer.style.textAlign = 'center';
                errorContainer.style.marginBottom = '15px';
                loginForm.insertBefore(errorContainer, loginForm.firstChild);
            } finally {
                loginButton.disabled = false;
                loginButton.style.opacity = '1';
                loginButton.textContent = '登录';
            }
        }
    });

    // Background zoom effect
    const background = document.querySelector('.background-container');
    let isZoomed = false;

    const toggleZoom = () => {
        isZoomed = !isZoomed;
        background.style.transform = isZoomed ? 'scale(1.2)' : 'scale(1.1)';
    };

    setInterval(toggleZoom, 20000);

    // Social login buttons hover effect
    const socialButtons = document.querySelectorAll('.social-btn');
    socialButtons.forEach(button => {
        button.addEventListener('mouseenter', () => {
            button.style.transform = 'translateY(-3px)';
        });

        button.addEventListener('mouseleave', () => {
            button.style.transform = 'translateY(0)';
        });
    });
}); 